import originAxios from 'axios';
import { message } from 'antd';

const axios = originAxios.create({
  timeout: 20000
})

axios.interceptors.response.use(
  function(response) {
    if (response.data && response.data.flag === 1) {
      /*
       * 同后端定义的接口返回形式
       * successful response: {"flag": 0, "data": ""}
       * unsuccessful response {"flag": 1, msg: "server error"}
      **/
      let errorMsg = response.data.msg;
      message.error(errorMsg);
      return Promise.reject(errorMsg);
    }
    return response.data;
  },
  function(error) {
    return Promise.reject(error);
  }
)

export function get(url: string, data: any) {
  return axios.get(url, {
    params: data
  })
}

export function post(url: string, data: any) {
  // 这里没有axios的post方法是因为axios.post方法会将请求数据默认转成json格式，以下方式是表单格式的post请求, 后端无需做解析了
  return axios({
    method: 'post',
    url,
    data
  })
}